import Singleton from '../base/Singleton'
/** 事件中心 保存各个节点需要触发的事件 */
interface IEvent {
  func: Function // 回调函数
  ctx: any // 上下文 this
}
export default class EventMgr extends Singleton {
  static get Instance() {
    return super.getInstance<EventMgr>()
  }

  eventMap: Map<string, Array<IEvent>> = new Map()

  on(eventName: string, func: Function, ctx?: any) {
    if (!this.eventMap.has(eventName)) {
      this.eventMap.set(eventName, [{ func, ctx }])
    } else {
      this.eventMap.get(eventName).push({ func, ctx })
    }
  }

  emit(eventName: string, ...args: any[]) {
    if (this.eventMap.has(eventName)) {
      this.eventMap.get(eventName).forEach(({ func, ctx }) => {
        ctx ? func.apply(ctx, args) : func(...args)
      })
    }
  }

  off(eventName: string, func: Function) {
    if (this.eventMap.has(eventName)) {
      const index = this.eventMap.get(eventName).findIndex(item => item.func === func)
      index > -1 && this.eventMap.get(eventName).splice(index, 1)
    }
  }

  clear() {
    this.eventMap.clear()
  }
}
